package com.pkx.cloud.fse7.conf;



import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @Description
 * @Author chenwg
 * @date 2020.11.04 16:49
 */
public class CustomDateConverter {
    public static class LocalDateConvert implements Converter<String, LocalDate> {
        @Override
        public LocalDate convert(String timestamp) {
            if (StringUtils.isNumeric(timestamp)) {
                // 如果是时间戳形式
                return Instant.ofEpochMilli(Long.valueOf(timestamp)).atZone(ZoneOffset.ofHours(8)).toLocalDate();
            } else if (timestamp.matches(CustomDateSerializerConfig.MATCHES_YYYY_MM_DD)) {
                // 如果是 yyyy-MM-dd 形式
                return LocalDate.parse(timestamp, DateTimeFormatter.ISO_LOCAL_DATE);
            } else {
                return null;
            }
        }
    }

    public static class LocalDateTimeConvert implements Converter<String, LocalDateTime> {
        @Override
        public LocalDateTime convert(String timestamp) {
            if (StringUtils.isNumeric(timestamp)) {
                // 如果是时间戳形式
                return LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf(timestamp)), ZoneId.systemDefault());
            } else if (timestamp.matches(CustomDateSerializerConfig.MATCHES_YYYY_MM_DD_HH_MM_SS)) {
                // 如果是 yyyy-MM-dd HH:mm:ss 形式
                return LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern(CustomDateSerializerConfig.YYYY_MM_DD_HH_MM_SS));
            } else if (timestamp.matches(CustomDateSerializerConfig.MATCHES_YYYY_MM_DD)) {
                // 如果是 yyyy-MM-dd 形式
                return LocalDate.parse(timestamp, DateTimeFormatter.ISO_DATE).atStartOfDay();
            } else {

                return null;
            }
        }
    }

    public static class DateConvert implements Converter<String, Date> {
        @Override
        public Date convert(String timestamp) {
            if (StringUtils.isNumeric(timestamp)) {
                // 如果是时间戳形式
                return new Date(Long.valueOf(timestamp));
            } else if (timestamp.matches(CustomDateSerializerConfig.MATCHES_YYYY_MM_DD_HH_MM_SS)) {
                // 如果是 yyyy-MM-dd HH:mm:ss 形式
                return CustomDateSerializerConfig.parseDate(timestamp, CustomDateSerializerConfig.YYYY_MM_DD_HH_MM_SS);
            } else if (timestamp.matches(CustomDateSerializerConfig.MATCHES_YYYY_MM_DD)) {
                // 如果是 yyyy-MM-dd 形式
                return CustomDateSerializerConfig.parseDate(timestamp, CustomDateSerializerConfig.YYYY_MM_DD);
            } else {
                return null;
            }
        }
    }
}
